package cn.myschool.web;

import cn.myschool.entity.Admin;
import cn.myschool.entity.Grade;
import cn.myschool.entity.Subject;
import cn.myschool.pojo.AjaxResult;
import cn.myschool.pojo.ExamResult2;
import cn.myschool.pojo.Page;
import cn.myschool.pojo.Subject2;
import cn.myschool.service.AdminService;
import cn.myschool.service.GradeService;
import cn.myschool.service.StudentService;
import cn.myschool.service.SubjectService;
import cn.myschool.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
//@WebServlet("/do/*")
@WebServlet("*.do")
public class CommonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        PrintWriter writer = resp.getWriter();
//        writer.println("<html>");
//        writer.println("<body>");
//        writer.println("<h1>上下文根："+req.getContextPath()+"</h1>");
//        writer.println("<h1>Qing求路径："+req.getServletPath()+"</h1>");
//        writer.println("<h1>URL："+req.getRequestURL()+"</h1>");
//        writer.println("<h1>URI："+req.getRequestURI()+"</h1>");
//        writer.println("<h1>pathInfo："+req.getPathInfo()+"</h1>");
//        String path=req.getServletPath();
//        path=path.substring(1,path.length()-3);
//        if(path.equals("login")){
//            writer.println("<h1 style='color:red;'>这是登录操作</h1>");
//            this.login(resp,req);
//        }else if(path.equals("updatesubject")){
//            writer.println("<h1 style='color:red;'>这是课程更新操作</h1>");
//            this.updatesubject(resp,req);
//        }else if(path.equals("delsubject")){
//            writer.println("<h1 style='color:red;'>这是课程删updatesubject除操作</h1>");
//        }else if(path.equals("addsubject")){
//            writer.println("<h1 style='color:red;'>这是课程增加操作</h1>");
//        }else{
//            writer.println("<h1 style='color:red;'>未知操作</h1>");
//        }
//        writer.println("</body>");
//        writer.println("</html>");
        String path = req.getServletPath();
        path = path.substring(1, path.length() - 3);
        //反射
        try {
            Method method = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            Object invoke = method.invoke(this, resp, req);
            if(invoke==null||StrUtil.isBlank(invoke))
                return;
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().print(JSON.toJSONStringWithDateFormat(invoke,"yyyy-MM-dd", SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty));
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(500, "方法" + path + "不支持");
        }

    }

    public void login(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String uname = req.getParameter("loginname");
        String upass = req.getParameter("upass");
        Admin admin = AdminService.ME.login(uname, upass);
        if (admin != null) {
            req.getSession().setAttribute("USER_LOGIN", admin);
            resp.sendRedirect("welcome.jsp");
            return;
        }
        req.setAttribute("msg", "错误的用户名或者密码！");
        req.getRequestDispatcher("/denglu.jsp").forward(req, resp);
    }

    public void subject(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String subname = StrUtil.toStr(req.getParameter("subjectname"));

        int pageNo = StrUtil.toInt(req.getParameter("pageNo"), 1);
        if (pageNo < 1) {
            resp.sendError(401, "分页条件错误");
            return;
        }
        Page<Subject2> p = SubjectService.ME.paging(pageNo, subname);

        req.setAttribute("subname", subname);
        req.setAttribute("p", p);

        req.getRequestDispatcher("/WEB-INF/jsp/subject.jsp").forward(req, resp);

    }

    public void updatesubject(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        resp.getWriter().println("待实现");
    }

    public void student(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        resp.getWriter().println("待实现");
    }

    public void toAddStudent(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        resp.getWriter().println("待实现");
    }

    public void addstudent(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        resp.getWriter().println("待实现");
    }

    public void showScore(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        long stuno = StrUtil.toLong(req.getParameter("stuno"), -1L);
        req.setAttribute("student", StudentService.ME.get(stuno));
        int pageNo = StrUtil.toInt(req.getParameter("pageNo"), 1);
        Page<ExamResult2> scores = StudentService.ME.findScore(stuno, pageNo);
        req.setAttribute("scores", scores);
        req.setAttribute("stuno", stuno);
        req.getRequestDispatcher("/WEB-INF/jsp/student/scores.jsp").forward(req, resp);
    }

    public void checkSubjectName(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String name = req.getParameter("subjectname");
        boolean b = SubjectService.ME.checkName(name);
//        try {
//            Thread.sleep(4000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        resp.getWriter().print(b);//发给浏览器,xhr.responseText获得
        resp.sendError(500);
    }

    public void grades(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        List<Grade> all = GradeService.ME.findALL();
        try {
            Thread.sleep(1800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        for (int i = 0; i < all.size(); i++) {
            Grade g = all.get(i);
            sb.append("{");
            sb.append("\"id\":" + g.getId());
            sb.append(",\"gname\":\"" + g.getGname() + "\"");
            sb.append("}");
            if (i < all.size() - 1)
                sb.append(",");
        }
        sb.append("]");
        System.out.println(sb);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(sb);
    }
    public void subjectajax(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {

        String subname= StrUtil.toStr(req.getParameter("subjectname"));

        int pageNo= StrUtil.toInt(req.getParameter("pageNo"),1);
//        if(pageNo<1){
//            resp.sendError(401,"分页条件错误");
//            return;
//        }
        Page<Subject2> p = SubjectService.ME.paging(pageNo, subname);
        resp.setContentType("application/json;charset=utf-8");
       resp.getWriter().println(JSON.toJSON(p));
    }
    public AjaxResult subjectAdd(HttpServletResponse resp, HttpServletRequest request) throws ServletException, IOException {
        String sbname = request.getParameter("subjectname");
        int sbhour = Integer.parseInt(request.getParameter("classhour"));
        int sbgid = Integer.parseInt(request.getParameter("gradeid"));
        int add = SubjectService.ME.add(new Subject(sbname, sbhour, sbgid));
        return add>0?AjaxResult.success():AjaxResult.error("课程名重复了！");
//        resp.setContentType("application/json;charset=utf-8");
//        request.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
        //  PrintWriter out = resp.getWriter();

//        if (add > 0) {
//            resp.getWriter().print(JSON.toJSON("true"));
//            //    out.println("<script>alert('增加课程成功！');window.location.replace('subject.html');</script>");
//        } else {
//            resp.getWriter().print(JSON.toJSON("false"));
//            //   out.println("<script>alert('增加课程失败！');window.history.back();</script>");
//        }
    }
    public AjaxResult findSubject(HttpServletResponse resp, HttpServletRequest request) throws ServletException, IOException {

        long id = StrUtil.toLong(request.getParameter("id"),-1L);
        Subject subject = SubjectService.ME.get(id);

        return subject==null?AjaxResult.error("对象不存在"):AjaxResult.success(subject);
    }
    public AjaxResult subjectUpdate(HttpServletResponse resp, HttpServletRequest request) throws ServletException, IOException {
        String sbname = request.getParameter("subjectname");
        int sbhour = Integer.parseInt(request.getParameter("classhour"));
        int sbgid = Integer.parseInt(request.getParameter("gradeid"));
        long id = Long.parseLong(request.getParameter("id"));
        int add = SubjectService.ME.update(new Subject(id,sbname, sbhour, sbgid));
        return add>0?AjaxResult.success():AjaxResult.error("更新课程出错了！");

    }
}
